<?php
/**
* Joomla! 1.5 component jhtraq
*
* @version $Id: view.html.php 2010-03-09 08:28:06 svn $
* @author JHShop
* @package Joomla
* @subpackage jhtraq
* @license GNU/GPL
*
* Traq type system for Joomla
*
*/

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.view');

/**
* HTML View class for the jhtraq component
*/
class JhtraqViewWiki extends JView {
	
	function display($tpl = null) 
	{
		$model =& JhtraqHelper::getModel('jhtraq');
		$project = JRequest::getVar('project');
		$this->project = $model->getProjectBySlug($project);
		
		$page = JRequest::getVar('page','Main_Page');
		JRequest::setVar('page',$page);
		$version = JRequest::getVar('version', 0);
		$this->wiki = $model->getWikiPage($page,$version,$this->project->id);
		$user =& JFactory::getUser();
		$task = JRequest::getVar('task');
		
		if($this->wiki->page_name == '' && $task == '')
		{
			if(JhtraqHelper::isAllowed($this->project->edit_wiki))
			{
				$task = 'edit';
			}else{
				$task = 'notfound';
			}
		}
		if($task != '')
		{
			$tpl = $this->$task();
		}else{
			$model->hitWiki($page,$this->project->id);
		}
		
		parent::display($tpl);
   }
   
   function notfound()
   {
	   return '404';
   }
   
   function savePage()
   {
	   $model =& JhtraqHelper::getModel('jhtraq');
	   $this->wiki = $model->updateWiki($this->wiki, $_POST, $this->project->id);
   }
   
   function edit()
   {
	   $document =& JFactory::getDocument();
	   $document->addScript(JURI::base() . "components/com_jhtraq/extras/jquery-1.3.2.min.js");
	   $document->addScript(JURI::base() . "components/com_jhtraq/extras/jquery.bbcodeeditor-1.0.min.js");
	   $document->addStyleSheet(JURI::base() . "components/com_jhtraq/extras/style.css");
	   return 'edit';
   }
   
   function adminactions()
   {
		   if(JhtraqHelper::isAllowed($this->project->edit_wiki))
		   {
			   return '| <a href="'.JRoute::_('index.php?option=com_jhtraq&view=wiki&task=edit&project=' . $this->project->slug . '&page=' . $this->wiki->page_name)  .'">'.JTEXT::_('COM_JHTRAQ_EDIT').'</a>';
		   }
	   return '';
   }
   

   
   function author($type = 'created_by')
   {
	   if((int) $this->wiki->$type == 0)
		 return JText::_('COM_JHTRAQ_GUEST');
	   
	   $db =& JFactory::getDBO();
	   $db->setQuery("Select username from #__users where id='".$this->wiki->$type . "'");
	   return $db->loadResult();
   }
   
   function created()
   {
	   return DATE("Y-m-d H:i", $this->wiki->created);
   }
   
   function modified()
   {
	   return DATE("Y-m-d H:i", $this->wiki->modified);
   }
   
   /**
    * TODO: clean up junk
	* TODO: Add special filters!!!
	*/
   function renderWikiBody()
   {
	   $body = "\n" . (stripslashes($this->wiki->body));
	   $content = $this->_onBeforeRenderWiki($body);
	   $return = $content;
	   $body = $this->_onAfterRenderWiki($return);
	   return $body;
   }
   
   function _onBeforeRenderWiki($body)
   {
	   $search = array(
				'/[^!]\[b\](.*?)\[\/b\]/is',
				'/[^!]\[i\](.*?)\[\/i\]/is',
				'/[^!]\[u\](.*?)\[\/u\]/is',
				'/[^!]\[img\](.*?)\[\/img\]/is',
				'/[^!]\[url\](http:\/\/|https:\/\/|svn:\/\/)(.*?)\[\/url\]/is',
				'/[^!]\[url\=(http:\/\/|https:\/\/|svn:\/\/)(.*?)\](.*?)\[\/url\]/is',
				'/[^!]\[url\](.*?)\[\/url\]/is',
				'/[^!]\[url\=(.*?)\](.*?)\[\/url\]/is',
				'/[^!]\[sub\](.*?)\[\/sub\]/is',
				'/[^!]\[sup\](.*?)\[\/sup\]/is',
				'/[^!]\[h1\](.*?)\[\/h1\]/is',
				'/[^!]\[h1\=(.*?)\](.*?)\[\/h1\]/is',
				'/[^!]\[h2\](.*?)\[\/h2\]/is',
				'/[^!]\[h2\=(.*?)\](.*?)\[\/h2\]/is',
				'/[^!]\[h3\](.*?)\[\/h3\]/is',
				'/[^!]\[h3\=(.*?)\](.*?)\[\/h3\]/is',
				'/[^!]\[h4\](.*?)\[\/h4\]/is',
				'/[^!]\[h4\=(.*?)\](.*?)\[\/h4\]/is',
				'/[^!]\[h5\](.*?)\[\/h5\]/is',
				'/[^!]\[h5\=(.*?)\](.*?)\[\/h5\]/is',
				'/[^!]\[h6\](.*?)\[\/h6\]/is',
				'/[^!]\[h6\=(.*?)\](.*?)\[\/h6\]/is',
				'/[^!]\[code\=(.*?)\](.*?)\[\/code\]/is',
				'/[^!]\[code\](.*?)\[\/code\]/is',
				'/[^!]\[quote\](.*?)\[\/quote\]/is',
				'/[^!]\[size\=(.*?)\](.*?)\[\/size\]/is',
				'/[^!]\[list\=(.*?)\](.*?)\[\/list\]/is',
				'/[^!]\[list\](.*?)\[\/list\]/is',
				'/[^!]\[\*\](.*?)\\n/is',
				'/[^!]{#(\d)}/s', //ticket links: eg {#23}
				'/[^!]{ticket:(\d)}/s', //ticket links: eg {ticket:23}
				'/[^!]{milestone:(.*?)}/is', //milestone links: eg{milestone:a1alpha}
				'/[^!]{@(.*?)}/is', //milesonte links: eg {@aiAlpha}
				'/[^!]\[back\]/is',
		);
										
		$replace = array(
				'<strong>$1</strong>',
				'<em>$1</em>',
				'<u>$1</u>',
				'<img src="$1" rel="shadowbox" class="wikiimg"/>',
				'<a href="$1$2">$2</a>',
				'<a href="$1$2">$3</a>',
				'<a href="index.php?option=com_jhtraq&view=wiki&project='.$this->project->slug.'&page=$1">$1</a>',
				'<a href="index.php?option=com_jhtraq&view=wiki&project='.$this->project->slug.'&page=$1">$2</a>',
				'<sub>$1</sub>',
				'<sup>$1</sup>',
				'<h1>$1</h1>',
				'<h1 class="$1">$2</h1>',
				'<h2>$1</h2>',
				'<h2 class="$1">$2</h2>',
				'<h3>$1</h3>',
				'<h3 class="$1">$2</h3>',
				'<h4>$1</h4>',
				'<h4 class="$1">$2</h4>',
				'<h5>$1</h5>',
				'<h5 class="$1">$2</h5>',
				'<h6>$1</h6>',
				'<h6 class="$1">$2</h6>',
				'<pre xml: lang="$1">$2</pre>',
				'<pre>$1</pre>',
				'<blockquote>$1</blockquote>',
				'<span style="font-size:$1%;">$2</span>',
				'<ol>$2</ol>',
				'<ul>$1</ul>',
				'<li>$1</li>',
				'<A href="index.php?option=com_jhtraq&view=tickets&layout=view&project='.$this->project->slug.'&ticket=$1">#$1</a>',
				'<A href="index.php?option=com_jhtraq&view=tickets&layout=view&project='.$this->project->slug.'&ticket=$1">#$1</a>',
				'<a href="index.php?option=com_jhtraq&view=milestone&project='.$this->project->slug.'&milestone=$1">$1</a>',
				'<a href="index.php?option=com_jhtraq&view=milestone&project='.$this->project->slug.'&milestone=$1">$1</a>',
				'<A HREF="javascript:history.go(-1)">' . JText::_('Back') . '</A>'
		);
														 
		$body = preg_replace ($search, $replace, $body);
		
		$regex = "#<pre xml:\s*(.*?)>(.*?)</pre>#s";
		$body = preg_replace_callback( $regex, 'JHW_Geshi_replacer',  $body );
		
		return $body;	
   }
   
   function _onAfterRenderWiki($body)
   {
	   //geshi
	   $regex = '#<pre class="(.*?)">(.*?)</pre>#s';
	   $rexrep = '<pre class="$1" style=" width:90%;overflow:auto;max-height:300px;">$2</pre>';
	   $body = preg_replace($regex,$rexrep,$body);
	   
	   
	   $body = str_replace('![', '[', $body);
	   //ticket links #1
	   //eg {#23}
// 	   $regex = '/{#(\d)}/s';
// 	   $rexrep = '<A href="index.php?option=com_jhtraq&view=tickets&layout=view&project='.$this->project->slug.'&ticket=$1">#$1</a>';
// 	   $body = preg_replace($regex,$rexrep,$body);
	   
	   //milestone
	   //eg milestone:abc -slug
// 	   $regex = "/{milestone:(.*?)}/is";
// 	   $rexrep = '<a href="index.php?option=com_jhtraq&view=milestone&project='.$this->project->slug.'&milestone=$1">$1</a>';
// 	   $body = preg_replace($regex,$rexrep,$body);
	   
	   
	   $db =& JFactory::getDBO();
	 
	   $pattern = '/<a href=(.*?)>/';
	   preg_match_all($pattern, $body, $matches, PREG_OFFSET_CAPTURE, 3);
	  // print_r($matches);
	   if(count($matches))
	   {
		   $tests = array();
		   $m1 = $matches[0];
		   $m2 = $matches[1];
		   
		   $x = 0;
		   foreach($m2 as $i=>$v)
		   {
				$v = str_replace("'",'',str_replace('"',"",$v[0]));
				$t = substr($v,0,6);
				if($t != 'http:/' && $t != 'svn://' && $t != 'https:')
				{
					$u = parse_url($v);
					$q = explode("&",$u['query']);
					if(count($q))
					{
						foreach($q as $l)
						{
							if(substr($l,0,5) == 'page=')
							{
								$p = str_replace('page=','',$l);
								$tests[$p] = array("orig"=>$m1[$x][0]);
							}
						}
					}
				}else{
					$link = str_replace("<a href", '<a class="extlink" href', $m1[$x]);
					$body = str_replace($m1[$x], $link, $body);
				}
				$x++;
			}
			//print_r($tests);
			if($tests)
			{
				$db->setQuery("Select count(*) as cnt,page_name from #__jhtraq_wiki where (page_name like '".implode("' OR page_name like '", array_keys($tests)) ."') and project_id='".$this->project->id."' group by page_name");
				$res = $db->loadAssocList();
				//print_r($res);
				foreach($res as $row)
				{
					if($row['cnt'] > 0)
						unset($tests[$row['page_name']]);
				}
				
				foreach($tests as $test)
				{
					$link = str_replace('<a href', '<a class="redlink" href', $test['orig']);
					$body = str_replace($test['orig'], "$link", $body);
				}
				
			}
	   }

	   
	   return nl2br($body);
   }
   
   
   
}
function JHW_Geshi_replacer( &$matches )
{

	jimport('geshi.geshi');
	jimport('domit.xml_saxy_shared');
	
	$args = SAXY_Parser_Base::parseAttributes( $matches[1] );
	$text = $matches[2];
	
	$lang	= JArrayHelper::getValue( $args, 'lang', 'phpz' );
	$lines	= JArrayHelper::getValue( $args, 'lines', 'true' );
	
	$geshi = new GeSHi($text, $lang);
	$geshi->set_header_type(GESHI_HEADER_PRE);
	$geshi->enable_line_numbers( GESHI_NORMAL_LINE_NUMBERS );
		return '<code>' . $geshi->parse_code() . '</code>';

}
